//
//  ST_UIViewController+Swizzling.swift
//  BTVideo
//
//  Created by DouLei on 2019/7/26.
//  Copyright © 2019 DouLei. All rights reserved.
//

import Foundation
import SnapKit
import SwifterSwift
import MediaPlayer


let swizzling: (AnyClass, Selector, Selector) -> () = { forClass, originalSelector, swizzledSelector in
    let originalMethod = class_getInstanceMethod(forClass, originalSelector)
    let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector)
    method_exchangeImplementations(originalMethod!, swizzledMethod!)
}

/*
extension Bundle{
    
    
    static let FWMethodSwizzling: Void = {
        
        let originalSelector1 = #selector(url(forResource:withExtension:))
        
        let swizzledSelector1 = #selector(swizzled_url(forResource:withExtension:))
        
        swizzling(Bundle.self, originalSelector1, swizzledSelector1)
        
    }()
    
    
    @objc func swizzled_url(forResource name: String?, withExtension ext: String?) -> URL?{
     
        
//        if name?.contains(".bundle") == true{
//            print("[美颜包太大了]: bundle Name = ",name)
//        }
        
        
        
        return swizzled_url(forResource: name, withExtension: ext)
        
    }
    
}
*/

fileprivate let slideInTransitioningDelegate = ST_SlideInPresentationManager()

extension UIViewController {
    
    
    
    static let FWMethodSwizzling: Void = {
        
        let originalSelector1 = #selector(present(_:animated:completion:))
        
        let swizzledSelector1 = #selector(swizzled_present(_:animated:completion:))
        
        swizzling(UIViewController.self, originalSelector1, swizzledSelector1)
        
        let originalSelector2 = #selector(dismiss(animated:completion:))
        
        let swizzledSelector2 = #selector(swizzled_dismiss(animated:completion:))
        
        swizzling(UIViewController.self, originalSelector2, swizzledSelector2)
        
    }()
    
    
//    MARK: - Present to Controller
    private struct ST_ControllerAssociatedKeys {
        static var maskViewKey: UInt8 = 9
        static var over_current_context_key: UInt8 = 93
        static var over_current_context_alpha_key: UInt8 = 97
    }
    
    
    /**
     是否是遮罩类型的模态跳转
     */
    @objc var overCurrentContext:Bool{
        get {
            if let value = objc_getAssociatedObject(self, &ST_ControllerAssociatedKeys.over_current_context_key) as? Bool{
                return value
            }else{
                return false
            }
        }
        set(newValue) {
            objc_setAssociatedObject(self, &ST_ControllerAssociatedKeys.over_current_context_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
        }
    }
    
    
   @objc var over_current_context_alpha:String{
        get {
            if let value = objc_getAssociatedObject(self, &ST_ControllerAssociatedKeys.over_current_context_alpha_key) as? String{
                return value
            }else{
                return "0.7"
            }
        }
        set(newValue) {
            objc_setAssociatedObject(self, &ST_ControllerAssociatedKeys.over_current_context_alpha_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    
    @objc func swizzled_present(_ viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)? = nil){
        
        
        NotificationCenter.default.post(name: Notification.Name.global_present_controller, object: nil, userInfo: ["fromController":self,"toController":viewControllerToPresent])
        
        ST_TIANRouteMonitor.default.didChanged.onNext(.will(type: .present, value: ST_TIANPushStatus.RouteValue(form: self, to: viewControllerToPresent)))
        
        let cStr = String(describing: viewControllerToPresent)
        
        if cStr.contains("ShanYanAuth"){
            
            swizzled_present(viewControllerToPresent, animated: false) {
                
                completion?()
                
                ST_TIANRouteMonitor.default.didChanged.onNext(.finished(type: .present, value: ST_TIANPushStatus.RouteValue(form: self, to: viewControllerToPresent)))
            }
            
            return
        }
        
        ST_SwiftyFloatingWidget.provider.currentWindow?.isUserInteractionEnabled = false
        
        if viewControllerToPresent.overCurrentContext == false{
            
            swizzled_present(viewControllerToPresent, animated: flag) {
                
                ST_SwiftyFloatingWidget.provider.currentWindow?.isUserInteractionEnabled = true
                
                completion?()
                
                ST_TIANRouteMonitor.default.didChanged.onNext(.finished(type: .present, value: ST_TIANPushStatus.RouteValue(form: self, to: viewControllerToPresent)))
                
            }
            
            
        }else{
            
            viewControllerToPresent.transitioningDelegate = slideInTransitioningDelegate
            
            viewControllerToPresent.modalPresentationStyle = .custom
            
            swizzled_present(viewControllerToPresent, animated: flag) {
                
                ST_SwiftyFloatingWidget.provider.currentWindow?.isUserInteractionEnabled = true
                
                completion?()
                
                ST_TIANRouteMonitor.default.didChanged.onNext(.finished(type: .present, value: ST_TIANPushStatus.RouteValue(form: self, to: viewControllerToPresent)))
                
            }
            
        }
    }
    
    @objc func swizzled_dismiss(animated flag: Bool, completion: (() -> Void)? = nil){
        
        
        ST_SwiftyFloatingWidget.provider.currentWindow?.isUserInteractionEnabled = false
        
        if ((self.presentedViewController as? UIAlertController) != nil){
            
            swizzled_dismiss(animated: flag) {
                
                if let topmostVC = TopmostViewController(){
                    
                    NotificationCenter.default.post(name: Notification.Name.goback_topmost_controller, object: nil, userInfo: ["controller":topmostVC])
                    
                    
                    ST_TIANRouteMonitor.default.didChanged.onNext(.finished(type: .dismiss, value: ST_TIANPushStatus.RouteValue(form: self, to: topmostVC)))
                    
                }
                
                ST_SwiftyFloatingWidget.provider.currentWindow?.isUserInteractionEnabled = true
             
                completion?()
                
            }
            
        }else{
            
          
//            print("关闭动画不好看----",self.transitioningDelegate)
            
            var f = flag
            
//            没有动画的时候
            if self.transitioningDelegate is ST_SlideInPresentationManager && f == false{
                
                f = true
                
                slideInTransitioningDelegate.direction = .none
                
            }else{
                
                slideInTransitioningDelegate.direction = .bottom
            }
            
//            print("[关闭动画卡死]---开始Controller=",TopmostViewController())
            
            swizzled_dismiss(animated: f) {
                
//                dismiss 之后 还是自己
                if TopmostViewController() == self {
                    
//                    print("[关闭动画卡死]---没有把自己关闭")
                    
                    self.swizzled_dismiss(animated: f) {
                        ST_SwiftyFloatingWidget.provider.currentWindow?.isUserInteractionEnabled = true
                        completion?()
                    }
                    
                    return
                }
                
                if let topmostVC = TopmostViewController(){
                    
                    NotificationCenter.default.post(name: Notification.Name.goback_topmost_controller, object: nil, userInfo: ["controller":topmostVC])
                    
//                    print("[关闭动画卡死]---结束Controller=",topmostVC)
                    
                    
                    ST_TIANRouteMonitor.default.didChanged.onNext(.finished(type: .dismiss, value: ST_TIANPushStatus.RouteValue(form: self, to: topmostVC)))
                    
                }
                
                ST_SwiftyFloatingWidget.provider.currentWindow?.isUserInteractionEnabled = true
                completion?()
            }
            
//            swizzled_dismiss(animated: flag, completion: completion)
        }
    }
    
}

